#/usr/bin/perl                                                                                                                           

%cidhash;

# Read the log file and store 1703 unique clone ids
for $sw ($ARGV[0]..$ARGV[1]){
    # Store ms pattern at each time step 
    %cidhash=();
    open (i1,"sweep$sw/sweep$sw.log");
    while(<i1>){
	chomp;
	@row=split(/\,/);
	if($row[2]==$day){
	    $cid = $row[1];
	    if(!defined($cidhash{$cid})){
		$cidhash{$cid}=1;
	    }
	}
    }
    close i1;    
}

%patterns;

for $sw ($ARGV[0]..$ARGV[1]){

    %patterns=();

    # Load all patterns in memory
    open (in,"sweep$sw/sweep$sw.patterns");
    while(<in>){
	chomp;
	@row=split(/\,/);
	# Skip loading cloneids from other timepoints
	if($cidhash{$row[0]}){
	    $patterns{$row[0]}="";
	    for my $loc (0..243){
		# Add to an array
		# Pattern is locus_id.ms_length.locus_id.ms_length
		# where length 100 is ignored
		if($row[$loc+1]!=100){
		    $patterns{$row[0]}=$patterns{$row[0]}.($loc+1).$row[$loc+1]; 
		}
	    }
	}
    }
    close in;
    # Dead cells have cid=-1 so they have no pattern
    $patterns{-1}="";

    my $day = 7300; 
    
    # Store ms pattern at each time step 
    %pathash=();
    $pat_count = 0;
    open (i1,"sweep$sw/sweep$sw.log");
    open (out, ">sweep$sw/sweep$sw.grid");
    while(<i1>){
	chomp;
	@row=split(/\,/);
	if($row[2]==$day){
	    
	    $pat = "";
	    $cid = $row[1];
	    # get the pattern from hash
	    $pat = $patterns{$cid};
	    if(!defined($pathash{$pat})){
		$pat_count++;
		$pathash{$pat}=$pat_count;
	    }
	    print out $row[0].",".$pathash{$pat}.",".$row[2]."\n";
	}
    }
    close i1;    
    close out;    
}

    
